<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button type="primary" @click="showAddRoles">添加角色</el-button>

      <!-- 表格 -->
      <el-table :data="rolesData" border stripe style="width: 100%">
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 展开行的标签组 -->

            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="['vcenter', index === 0 ? 'bd_top' : '', 'bd_bottom']"
            >
              <!-- 一级菜单 -->
              <el-col :span="6">
                <el-tag closable>{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级菜单 -->
              <el-col :span="12">
                <el-row
                  v-for="(item2, index2) in item.children"
                  :key="item2.id"
                  :class="index2 === 0 ? '' : 'bd_top'"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable>{{ item2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级菜单 -->
                  <el-col :span="12">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 排序行 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="showEditRoles(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showDistRoles(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
        <!-- 表单 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRolesData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改角色对话框 -->
      <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%">
        <!-- 表单 -->
        <el-form
          :model="editForm"
          :rules="addFormRules"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRolesData">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="distDialogVisible" width="50%">
        <!-- 树形控件 -->
        <el-tree
          ref="distRolesRef"
          :data="rightsList"
          show-checkbox
          node-key="id"
          :default-expanded-keys="checkedKeys"
          :default-checked-keys="checkedKeys"
          :props="defaultProps"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="distDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="distRolesData">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      // 角色数据
      rolesData: [],
      // 添加角色的信息
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      addDialogVisible: false,
      // 修改与添加共用
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },

      // 修改角色信息
      editDialogVisible: false,
      editForm: {
        roleName: "",
        roleDesc: "",
      },
      editId: "",

      // 分配权限
      distDialogVisible: false,
      distId: "",
      rightsList: [],
      checkedKeys: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
    };
  },
  created() {
    this.getRolesData();
    this.getRightsList();
  },
  methods: {
    // 获取角色数据
    async getRolesData() {
      const { data: res } = await this.$http.get(`roles`);
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");

      this.rolesData = res.data;
    },
    // 开始对话框
    showAddRoles() {
      this.addDialogVisible = true;
    },
    // 添加角色信息
    addRolesData() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写角色名称");
        const { data: res } = await this.$http.post("roles", {
          roleName: this.addForm.roleName,
          roleDesc: this.addForm.roleDesc,
        });

        if (res.meta.status !== 201) return this.$message.error("创建失败");

        this.$message.success("创建成功");
        this.addDialogVisible = false;
        this.getRolesData();
      });
    },
    // 开启修改对话框
    showEditRoles(row) {
      this.editDialogVisible = true;
      this.editId = row.id;
      this.editForm.roleName = row.roleName;
      this.editForm.roleDesc = row.roleDesc;
    },
    // 修改角色信息
    editRolesData() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写角色名称");
        const { data: res } = await this.$http.put(`roles/${this.editId}`, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc,
        });
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("修改失败");

        this.$message.success("修改成功");
        this.editDialogVisible = false;
        this.getRolesData();
      });
    },
    // 删除角色信息
    async deleteRole(row) {
      const confirmStr = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmStr !== "confirm") {
        return this.$message.info("您取消了删除操作");
      }
      const { data: res } = await this.$http.delete(`roles/${row.id}`);
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("删除失败");

      this.$message.success("删除成功");
      this.getRolesData();
    },
    // 获取权限列表
    async getRightsList() {
      const { data: res } = await this.$http.get(`rights/tree `);
      this.rightsList = res.data;
    },
    // 开启分配权限对话框
    showDistRoles(row) {
      this.distDialogVisible = true;
      this.distId = row.id;
      this.distData = row.children;
      this.getCheckedKeys(row, this.checkedKeys);
    },

    //把拥有的权限放checkedKeys中
    getCheckedKeys(roles, arr) {
      //  如果是三级权限  则添加到arr
      if (!roles.children) {
        return arr.push(roles.id);
      }
      // 如果不是三级 在让其children 执行
      roles.children.forEach((item) => {
        this.getCheckedKeys(item, arr);
      });
    },
    // 分配权限
    async distRolesData() {
      const arr = [
        ...this.$refs.distRolesRef.getCheckedKeys(),
        ...this.$refs.distRolesRef.getHalfCheckedKeys(),
      ];
      const { data: res } = await this.$http.post(
        `roles/${this.distId}/rights`,
        {
          rids: arr.join(","),
        }
      );

      if (res.meta.status !== 200) return this.$message.error("更新失败");

      this.$message.success("更新成功");
      this.getRolesData();
      this.distDialogVisible = false;
    },
  },
};
</script>

<style>
</style>